/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.ArrayList;
import model.Thanhvien;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import util.HibernateUtil;

/**
 *
 * @author HoangLiem
 */
public class ThanhVienDAO {

    public static ArrayList<Thanhvien> getAllUsers() {
        ArrayList<Thanhvien> list = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            Transaction trans = session.getTransaction();
            trans.begin();
            String hql = "from Thanhvien";
            Query query = session.createQuery(hql);
            list = (ArrayList<Thanhvien>) query.list();
            trans.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return list;
    }

    public static Thanhvien logIn(String tenDangNhap, String matKhau) {
        Thanhvien tv = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            Transaction trans = session.getTransaction();
            trans.begin();
            String hql = "from Thanhvien tv where tv.tenDangNhap=:tenDangNhap and tv.matKhau=:matKhau";
            Query query = session.createQuery(hql);
            query.setString("tenDangNhap", tenDangNhap);
            query.setString("matKhau", matKhau);
            tv = (Thanhvien) query.uniqueResult();
            trans.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return tv;
    }

    public static Thanhvien getUserById(String tenDangNhap) {
        Thanhvien tv = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            Transaction trans = session.getTransaction();
            trans.begin();
            String hql = "from Thanhvien tv where tv.tenDangNhap=:tenDangNhap ";
            Query query = session.createQuery(hql);
            query.setString("tenDangNhap", tenDangNhap);
            tv = (Thanhvien) query.uniqueResult();
            trans.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return tv;
    }

    public static boolean insertUser(Thanhvien tv) {
        boolean result = false;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = session.getTransaction();//session.beginTransaction();     
        try {
            trans.begin();
            session.save(tv);
            result = true;
            trans.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            result = false;
        }
        return result;
    }
}
